package com.xzy.shop.web.servlet;

import com.xzy.shop.domain.Cart;
import com.xzy.shop.domain.Goods;
import com.xzy.shop.domain.User;
import com.xzy.shop.service.CartService;
import com.xzy.shop.service.GoodsService;
import com.xzy.shop.service.impl.CartServiceImpl;
import com.xzy.shop.service.impl.GoodsServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/goods/*")
public class GoodsServlet extends BaseServlet {
    GoodsService service = new GoodsServiceImpl();
    CartService cartService = new CartServiceImpl();
    public void findAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<Goods> list = service.findAll();
        writeValue(list, response);
    }

    public void findByGid(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String gid = request.getParameter("gid");
        Goods info = service.findByGid(gid);
        writeValue(info, response);
    }

    public void findByUid(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        User user = (User) request.getSession().getAttribute("loginUser");
        List<Cart> gids = cartService.findGidByUid(user.getUid() + "");

        List<Goods> list = new ArrayList<Goods>();
        for (Cart gid : gids) {
            Goods good = service.findByGid(gid.getGid() + "");
            list.add(good);
        }

        writeValue(list, response);
    }

    public void findByCid(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String cid = request.getParameter("cid");
        List<Goods> list = service.findByCid(cid);

        writeValue(list, response);
    }

    //模糊查询功能
    public void serchGoods(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String keywords = request.getParameter("keywords");
        List<Goods> list = service.serchGoods(keywords);
        writeValue(list, response);
    }
}
